package com.krtech.wecard.utils;

import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.krtech.wecard.framework.exception.BusinessException;
import com.krtech.wecard.module.sys.entity.SysKeyValue;
import com.krtech.wecard.module.sys.enums.SysEnums;
import com.krtech.wecard.module.sys.service.SysKeyValueService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashMap;

@Component
public class WxUtil {

    @Autowired
    private SysKeyValueService keyValueService;

    /**
     * 获得oauth小程序临时页面
     */
    public void getMipOauth2Page(){
        String accessToken = this.getAccessToken();

        String url = "https://api.weixin.qq.com/wxa/generatescheme?access_token="+accessToken;

        HttpRequest post = HttpUtil.createPost(url);

        HashMap<String, String> jumpWxa = new HashMap<>();
        jumpWxa.put("path","");
    }


    /**
     * 获得access_token
     */
    public String getAccessToken(){
        //获得appid和secret
        SysKeyValue appId = keyValueService.getOne(new QueryWrapper<SysKeyValue>()
                .eq(SysKeyValue.COL_SYS_NAME, SysEnums.WX_APPLETS_APPID));
        SysKeyValue secret = keyValueService.getOne(new QueryWrapper<SysKeyValue>()
                .eq(SysKeyValue.COL_SYS_NAME, SysEnums.WX_APPLETS_SECRET));

        String url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid="+appId.getSysValue()+"&secret="+secret.getSysValue();
        HttpRequest get = HttpUtil.createGet(url);
        HttpResponse execute = get.execute();
        String body = execute.body();

        JSONObject jsonObject = JSONUtil.parseObj(body);

        Object access_token = jsonObject.get("access_token");

        if (access_token == null){
            throw new BusinessException("获得微信accesstoken失败");
        }

        return access_token.toString();

    }
}
